package com.jwork.progress.service;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Service
public class ConsumerService {
    private static final Logger logger = LoggerFactory.getLogger(ConsumerService.class);

    public void showRecords() {
        Map<String, Object> consumerConf = new HashMap<>();
        consumerConf.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "10.1.0.253:9092,10.1.0.253:9093,10.1.0.253:9094");
        consumerConf.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        consumerConf.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        consumerConf.put(ConsumerConfig.GROUP_ID_CONFIG, "smiler");
        consumerConf.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(consumerConf);
        kafkaConsumer.subscribe(Collections.singletonList("First"));

        try {
            while (true) {
                ConsumerRecords<String, String> data = kafkaConsumer.poll(100);
                int i = 0;
                for (ConsumerRecord<String, String> datum : data) {
                    i++;
                    logger.info("查12312" + datum.key() + i + "：" + datum.value());
                }
            }
        } finally {
            kafkaConsumer.close();
        }
    }
}
